package cn.com.zpark.utils;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

/**
 * @PackageName: cn.com.zpark.utils
 * @ClassName: DruidUtils
 * @Description:
 * @author: RZS
 * @date: 2021/12/11  15:21
 */
public class DruidUtils {
    // 定义数据源
    private static DataSource dataSource;

    // 初始化数据源
    static {
        // 获取配置文件流对象
        InputStream stream = DruidUtils.class.getClassLoader().getResourceAsStream("druid.properties");
        // 创建properties对象
        Properties p = new Properties();

        try {
            // 加载配置文件
            p.load(stream);
            // 初始化数据源
            dataSource = DruidDataSourceFactory.createDataSource(p);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                // 关闭资源
                stream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 获取数据库连接对象
     * @return
     * @throws Exception
     */
    public static Connection getConn() throws Exception {
        return dataSource.getConnection();
    }

    /**
     * 关闭资源
     */
    public static void close(ResultSet res, Statement stat, Connection conn){
        if(res != null){
            try {
                res.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if(stat != null){
            try {
                stat.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if(conn != null){
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
